package com.yuan.condition;

import com.yuan.bean.Student;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @Author: Jinsheng·yuan
 * @CreateDate: 2020/1/14 22:48
 * @Description: 通过实现ImportBeanDefinitionRegistrar接口,手动注册bean到容器中
 */
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    /**
     *
     * @param importingClassMetadata 当前类的注解信息
     * @param registry BeanDefinition注册类
     * @param importBeanNameGenerator
     */
   /* @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {

    }*/

    /**
     *
     * @param importingClassMetadata 当前类的注解信息
     * @param registry BeanDefinition注册类，
     *        把所有需要添加到容器中的Bean，用 registry.registerBeanDefinition()手工注册进来
     *
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //registry.registerBeanDefinition();
        boolean red = registry.containsBeanDefinition("com.yuan.bean.Red");
        boolean blue = registry.containsBeanDefinition("com.yuan.bean.Blue");
        //如果存在Red与Blue类,则注册自定义的student类
        if(red && blue){
            //指定bean的定义信息(就是Bean的类型)
            RootBeanDefinition beanDefinition = new RootBeanDefinition(Student.class);
            //自定义bean的名字为student
            registry.registerBeanDefinition("student",beanDefinition);
        }
    }
}
